﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wicresoft.SMS.Common;

namespace Wicresoft.SMS.Data
{
    public class ReminderService
    {
        private IConnectStringProvider connProvider;
        public ReminderService(IConnectStringProvider connectProvider)
        {
            connProvider = connectProvider;
        }

        //0:s
        //> 0 failed
        public int SetUserMobilePhone(string email, string mobile)
        {
            using (var db = new Entities(connProvider.ConnectionString))
            {
                var user = db.User.FirstOrDefault(p => p.Email == email);
                if (user == null)
                    return 1;
                user.Mobile = mobile;
                db.SaveChanges();
            }
            return 0;
        }

        public void DeleteNoSendReminders(string email)
        {
            using (var db = new Entities(connProvider.ConnectionString))
            {
                //cp_delete_nosend_reminder
                System.Data.Objects.ObjectParameter outs = new System.Data.Objects.ObjectParameter("outs", System.Data.DbType.Int32);
                db.cp_delete_nosend_reminder(email, outs);
            }

        }

        public void InsertReminder(string entryKey, string email, string content, decimal reminderTime, decimal startTime, decimal endTime)
        {
            using (var db = new Entities(connProvider.ConnectionString))
            {
                //cp_add_reminde
                System.Data.Objects.ObjectParameter outs = new System.Data.Objects.ObjectParameter("outs", System.Data.DbType.Int32);
                db.cp_add_reminder(email,
                    entryKey, 
                    content,
                    DateTime.FromOADate((double)reminderTime),
                    DateTime.FromOADate((double)startTime),
                    DateTime.FromOADate((double)endTime),
                    outs);
            }

        }

        /// <summary>
        /// cp_reminder_send
        /// </summary>
        /// <returns>0:s 1:f</returns>
        public int SendReminder()
        {
            System.Data.Objects.ObjectParameter outs = new System.Data.Objects.ObjectParameter("outs", System.Data.DbType.Int32);
            try
            {
                using (var dbModel = new Entities(connProvider.ConnectionString))
                {
                    dbModel.cp_reminder_send(outs);
                }
            }
            catch (Exception ex)
            {
                Logger.Debug("SendReminder: " + ex.ToString());
                return 1;
            }
            return Convert.ToInt32(outs.Value);
        }

    }
}
